﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Security.Principal;
using System.Linq;
using System.Windows.Navigation;
using System.Windows.Browser;
using AuthorizedNavigation.Client.Views.ChildWindowViews;
using AuthorizedNavigation.Client.Services;
using AuthorizedNavigation.Client.ViewModels;
using AR;
using AR.Error;

namespace AuthorizedNavigation.Client
{
    public class AuthenticationContext : DependencyObject, IAuthenticationContext
    {


        public static DependencyProperty UserProperty =
        DependencyProperty.Register("User",
                                    typeof(IPrincipal),
                                    typeof(AuthenticationContext),
                                    new PropertyMetadata(null));
        
        public IPrincipal User
        {
            get { return (IPrincipal)this.GetValue(UserProperty); }
            set { this.SetValue(UserProperty, value); }
        }


        public static DependencyProperty ShowLoginBoxWhenUnauthorizedProperty =
      DependencyProperty.Register("ShowLoginBoxWhenUnauthorized",
                                  typeof(bool),
                                  typeof(AuthenticationContext),
                                  new PropertyMetadata(false));

        public bool ShowLoginBoxWhenUnauthorized
        {
            get { return (bool)this.GetValue(ShowLoginBoxWhenUnauthorizedProperty); }
            set { this.SetValue(ShowLoginBoxWhenUnauthorizedProperty, value); }
        }




       public static DependencyProperty UriRightMappingsProperty =
       DependencyProperty.Register("UriRightMappings",
                                   typeof(DependencyObjectCollection<UriRightMapping>),
                                   typeof(AuthorizedContentLoader),
                                   new PropertyMetadata(new DependencyObjectCollection<UriRightMapping>()));




        public DependencyObjectCollection<UriRightMapping> UriRightMappings
        {
            get { return (DependencyObjectCollection<UriRightMapping>)this.GetValue(UriRightMappingsProperty); }
            set { this.SetValue(UriRightMappingsProperty, value); }
        }



        public bool CheckAuthenticationAndAuthorization(Uri targetUri, Uri currentUri)
        {
            // get mapping
            var mapping = this.UriRightMappings.FirstOrDefault(m => m.Matches(targetUri));

            // no mapping exists, navigation is allowed
            if (mapping == null)
                return true;

            var navigationAllowed = mapping.CanNavigate(User);

            if (!navigationAllowed && ShowLoginBoxWhenUnauthorized)
            {
                NavigationErrorWindow err;
                // show login, and afterwards, renavigate so the logic is executed again
                if (User.Identity.IsAuthenticated)
                {
                    if ((User.IsInRole("SolutionManager")) && targetUri.OriginalString.Equals("/Views/Candidat/CreationCandidat.xaml"))
                    {
                        err = new NavigationErrorWindow();
                        err.Error.Text = "Vous deverez avoir l'un des roles Practice Manager ou  Workforce Manager Pour Accéder a cette page";
                        err.Show();

                    }
                    if (targetUri.OriginalString.Equals("/Views/EntretienOrale/EntretienOrale.xaml") && (!User.IsInRole("SolutionManager")))
                    {
                        err = new NavigationErrorWindow();
                        err.Error.Text = "Vous deverez avoir le role Solution Manager Pour Accéder a cette page";
                        err.Show();
                    }

                }
                if (WebContext.Current.Authentication.User.Identity.IsAuthenticated)
                {
                    MessageBox.Show("test");
                }
                else
                {

                    LoginDialogService loginService = new LoginDialogService();
                    loginService.ShowDialog<LoginViewModel>((vm) =>
                        {
                            // log in
                            var loginOp = WebContext.Current.Authentication.Login(vm.UserName, vm.Password);
                            loginOp.Completed += (send, args)
                                =>
                            {
                                // navigate again: this will re-check the credentials and continue to the 
                                // correct page if you're logged in / got the required role


                                if (Application.Current.RootVisual is MainPage)
                                {

                                    if (targetUri.OriginalString.Equals("/Views/Candidat/ListeCandidats.xaml"))
                                        ((MainPage)(Application.Current.RootVisual)).ContentFrame.Navigate(new Uri("/ListeCandidats", UriKind.Relative));
                                    if (targetUri.OriginalString.Equals("/Views/Candidat/CreationCandidat.xaml") && (User.IsInRole("PracticeManager") || User.IsInRole("WorkforceManager")))
                                        ((MainPage)(Application.Current.RootVisual)).ContentFrame.Navigate(new Uri("/CreationCandidat", UriKind.Relative));
                                    if (targetUri.OriginalString.Equals("/Views/EntretienOrale/EntretienOrale.xaml") && User.IsInRole("SolutionManager"))
                                        ((MainPage)(Application.Current.RootVisual)).ContentFrame.Navigate(new Uri("/EntretienOrale", UriKind.Relative));
                                    if ((User.IsInRole("SolutionManager")) && targetUri.OriginalString.Equals("/Views/Candidat/CreationCandidat.xaml"))
                                    {
                                        err = new NavigationErrorWindow();
                                        err.Error.Text = "Vous deverez avoir l'un des rôles Practice Manager ou  Workforce Manager Pour Accéder à cette page";
                                        err.Show();
                                    }
                                    if (targetUri.OriginalString.Equals("/Views/EntretienOrale/EntretienOrale.xaml") && (!User.IsInRole("SolutionManager")))
                                    {
                                        err = new NavigationErrorWindow();
                                        err.Error.Text = "Vous deverez avoir le rôle Solution Manager Pour Accéder à cette page";
                                        err.Show();
                                    }

                                }


                            };

                            vm.Cleanup();
                        },
                        (vm) =>
                        {
                            // cancel login in - stay on the current page.
                            vm.Cleanup();
                        });

                }
            }

            return navigationAllowed;
        }

    }
}
